﻿using Gargoyle.Roton;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lyon
{
    public partial class MemoryViewer : Form
    {
        int offset = 0x2490;
        TextModeVideo video;

        public MemoryViewer()
        {
            InitializeComponent();
            video = new TextModeVideo(new Size(80, 25), null, null, false);
            video.SetBright(true);
            ClientSize = video.Bitmap.Size;
            BackgroundImage = video.Bitmap;
            tmrUpdate.Tick += Tick;
            tmrUpdate.Enabled = true;
        }

        public Memory Memory { get; set; }

        string Hex(int value, int places)
        {
            StringBuilder result = new StringBuilder();
            while (places > 0)
            {
                result.Insert(0, "0123456789ABCDEF".Substring(value & 0xF, 1));
                value >>= 4;
                places--;
            }
            return result.ToString();
        }

        void Tick(object sender, EventArgs e)
        {
            byte color = 0x0F;
            for (int y = 0; y < 25; y++)
            {
                video.WriteString(new Point(0, y), Hex(offset + (y << 4), 4), 0x0E);
                for (int x = 0; x < 16; x++)
                {
                    byte data = Memory.GetByte(offset + (y << 4) + x);
                    video.WriteString(new Point((x << 1) + 5, y), Hex(data, 2), (byte)(color | 0x80));
                    video.SetChar(new Point(x + 38, y), new AnsiChar(data, (byte)(color & 0xB | 0x10)));
                    color ^= 0x08;
                }
            }
            Invalidate();
        }
    }
}
